import { asyncRouterMap, asyncAdminRouterMap, asyncUserEditionMap, asyncChannleMap, 
  asyndailiMap,
  asyncPluginsMap, //应用
  constantRouterMap } from '@/router'
import qs from 'qs'
/**
 * @param roles
 * @param route
 */

/**
 * @param routes asyncRouterMap
 * @param roles
 */

const storeMenuHash = {
  channel: ['/channel'],
  plugin: ['/application'],
  dealer: ['/distribution', 'distributorApplication', 'distributorUser', 'distributorMerchandise', 'distributorMerchandiseSetting', 'distributorOrders', 'withdrawalApplication', 'distributorSetting', 'recycleDistributorUser'],
  wechat: ['weChatPublicChannel', 'weChatPublicChannelAdd', 'weChatMenuChannelAdd', 'weChatMenuChannelList', 'weChatReplyChannelList', 'weChatMenuChannelAdd', 'weChatPublicImageSource', 'weChatPublicVideoSource', 'weChatPublicAudioSource', 'weChatPublicUeditorSource', 'weChatPublicUeditorSourceAdd'],
  wxapp: ['weChatAppletsChannel', 'weChatAppletsChannelRedirect', 'weChatAppletsChannelPublish', 'weChatAppletsChannelQrcode', 'weChatAppletsChannelAdd'],
  aliapp: ['alipayAppletsChannel', 'alipayAppletsChannelAdd'],
  baiduapp: ['baiduAppletsChannel', 'baiduAppletsChannelAdd'],
  H5: ['h5Channel', 'h5ChannelAdd'],
  toutiaoapp: ['toutiaoAppletsChannel', 'toutiaoAppletsChannelAdd'],
  android: [],
  ios: [],
  spike: ['spikeMarketing', 'spikeMarketingAdd'],
  groups: ['groupsMarketing', 'groupsMarketingAdd', 'groupsInfoList'],
  luck: ['lottery', 'lotteryAdd', 'lotteryInfoList'],
  redenvelopes: ['envelope', 'envelopeAdd'],
  diyposter: ['custormPosterList', 'custormPosterListAdd', 'custormPosterDecoration'],
  voucher: ['couponClient', 'couponClientFissure', 'couponClientFixed', 'couponClientNew', 'couponClientOld'],
  coupon: ['couponMarketing', 'couponMarketingRecords', 'couponMarketingFullAdd', 'couponMarketingDiscountAdd', 'couponMarketingFreightAdd', 'couponMarketingRandomAdd', 'recycleCouponMarketing'],
  member: ['membershipCardClient', 'vipList', 'vipListAdd', 'vipUserList', 'vipGoodsList', 'vipSetting', 'vipCodeList', 'distributorVip'],
  cashback: ['cashback', 'cashbackAdd', 'cashbackInfo'],
  bargain: ['bargain', 'bargainAdd'],
  kammi: ['cardPassword', 'cardPasswordAdd', 'cardPasswordEdit', 'cardPasswordLibrary', 'ordersCardPasswordManagement'],
  message: ['messageTool', 'notification', 'smsSettings', 'notificationAdd', 'notificationDeal', 'notificationMarketing', 'notificationPlatform'],
  cgp: ['groupBuy', 'commityGoodsManagement', 'supplierManagement', 'settleManagement', 'leaderApplication', 'leaderManagement', 'withdrawApplication', 'stockManagement', 'supplierIncomeStatistics', 'leaderSetting'], // 社区团购授权
  theme: ['themeColor'], // 主题配色授权
  reserve: ['subscribeList'],// 预约授权
  form:['custormPosterform'],//自定义表单授权
  praise:['activityLike'],//活动点赞授权
  ticketing:['ticketing'],//票务平台授权
  assist:['treasure'],//任务宝授权
  blessing:['blessingBag'],//福袋授权
  agent:['proxysettings'],//代理授权
  festival:['themeconstruction'],//主题造节授权
  timeCoupon:['scrambleTime'],//限时抢券权限
  falseUrl:['cannonfodder'],//炮灰域名权限
  live:["livelist"],//直播权限
  free:['freeofCharge'],
  card_bag: ['cardBag'],
  phoneBill: ['phoneBill'],
  paymarketing:['paymentMarketing'],
}

function isStorePermission(roles, route, pathMap = []) {
  if (Array.isArray(roles) && roles.length > 0) {
    const { path } = route
    let hasPermission = false

    if (Array.isArray(pathMap) && pathMap.length > 0) {
      pathMap.map(item => {
        const { key, redirect } = item
        if (path === key) {
          route.redirect = `${path}/${redirect}`
        }
      })
    }

    if (!roles.includes(path)) {
      hasPermission = true
    }
    return hasPermission
  }
}

function isBasePermission(roles, route, pathMap = [], storeMap = [], checkMap = []) {
  if (Array.isArray(roles) && roles.length > 0) {
    const { path, meta } = route
    let hasPermission = false
    roles.map(menu => {
      if (pathMap.includes(path)) {
        const { checkList, isIndeterminates, checkAll, path: rolesPath } = menu
        if ((Array.isArray(checkList) && checkList.length > 0 && checkList.includes(path) && !storeMap.includes(path))) {
          if (checkList.length === 0 && meta) {
            route.meta.noDropdown = true
          } else {
            const [firstPage] = checkList
            const { groupConfig = {} } = meta || {}
            const { groupMenuTitle, groupTitle } = groupConfig
            if (firstPage) {
              if (groupMenuTitle && groupTitle) {
                route.meta.groupMenuTitle = groupMenuTitle
                route.meta.groupTitle = groupTitle
              }
            }
          }
          hasPermission = true
        } else {
          if (rolesPath === path) {
            if (isIndeterminates === 'true' || checkAll === 'true') {
              const [firstPage] = checkList
              if (firstPage) {
                route.redirect = `${path}/${firstPage}`
              }
              hasPermission = true
            }
          }
        }
      } else if (!storeMap.includes(path)) {
        hasPermission = true
      }
    })
    return hasPermission
  }
}

function filterBaseRouter(routes, roles, pathMap, storeMap, checkMap) { // 过滤没有权限的列表 循环过滤 直到没有子路由
  const res = []
  const hasArg = arguments.length === 5
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasArg ? isBasePermission(roles, tmp, pathMap, storeMap, checkMap) : isStorePermission(roles, tmp, pathMap)) {
      if (tmp.children) {
        tmp.children = hasArg ? filterBaseRouter(tmp.children, roles, pathMap, storeMap, checkMap) : filterBaseRouter(tmp.children, roles, pathMap)
      }
      res.push(tmp)
    }
  })

  return res
}

const permission = {
  state: {
    routers: constantRouterMap,
    INDEX_LAYOUT: false,
    isGroup: false,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, { routers, reset, is_super,rootState}) => { // 保存动态路由时 将静态路由和动态路由合并
      //处理地址栏中的aid
      
      // console.log('===============Cookies',rootState.user.h_aid)

      const hasAid = !!qs.parse(location.href.split('?')[1]).h_aid
      
      state.addRouters = routers.filter(route=>{
        // 处理应用，渠道，权限是否在代理端显示
        if(hasAid) {
          // return !['/permission','/channel','/agentsetting'].find(path => path === route.path)
          return !['/permission','/channel','/agentsetting'].find(path => path === route.path)
        }
        return true
      })
      // console.log('state.routers 0000',routers)
      //处理在代理端时，财务的显示，下面也是
      if(hasAid){
        routers.map(item=>{
          // console.log("kjfhdskjhfdkj第三方肯定是",item)
          if(item.path=="/finance"){
            item.hidden = false
          }
          //处理代理端数据的重定向地址，重定向地址为下载中心
          if(item.path=="/basicdata"){
            item.redirect = '/basicdata/downloadCenter'
          }
        })
      }
      const [dashboard] = constantRouterMap.filter(item => {
        return item.redirect === 'dashboard'
      })
      if ((is_super || is_super === 0) && is_super !== 1) {
        const { children: [Dashboard] } = dashboard
        if (reset) {
          dashboard.hidden = true
          if (Dashboard && Dashboard.meta) {
            const [{ redirect, path }] = routers
            Dashboard.meta.resetDashboard = redirect || path
          }
        } else {
          Dashboard.meta.resetDashboard = 'dashboard'
          dashboard.hidden = false
        }
      } else {
        const { children: [Dashboard] } = dashboard
        Dashboard.meta.resetDashboard = null
        dashboard.hidden = false
      }
      state.routers = constantRouterMap.concat(routers).filter(route=>{
        if(hasAid) {
          return !['/permission','/channel','/agentsetting'].find(path => path === route.path)
        }
        return true
      })
      if(hasAid){
        routers.map(item=>{
          // console.log("kjfhdskjhfdkj第三方肯定是",item)
          if(item.path=="/finance"){
            item.hidden = false
          }
           //处理代理端数据的重定向地址，重定向地址为下载中心
           if(item.path=="/basicdata"){
            item.redirect = '/basicdata/downloadCenter'
          }
        })
      }
      // console.log('state.routers 1111',state.routers)
    },
    SET_INDEX_LAYOUT: (state, INDEX_LAYOUT) => {
      state.INDEX_LAYOUT = INDEX_LAYOUT
    },
    SET_GROUP: (state, isGroup) => {
      state.isGroup = isGroup
    },
    SET_ROUTER_PATH(state, roles) {
      // console.log("较好的水电费",state,roles)
      state.routerPath = roles
    },
  },
  actions: {
    GenerateRoutes({ commit,rootState}, { roles, path: { jurisdiction, is_super } },) {
      /**
     * @param {Array} roles
     * @desc
     */
      const Cookies = require('js-cookie')
      // console.log("佛挡杀佛卡等级",rootState)
      return new Promise(resolve => {
        let resetDashboard = true
        let accessedRouters = []
        //大概意思为，是admin就走asyncAdminRouterMap，不然走asyncRouterMap
        // console.log("这是个啥？？？...",asyncRouterMap)
        const isRouterMap = roles.includes('admin') ? asyncAdminRouterMap : asyncRouterMap
        const pathMap = []
        const storeMap = []
        const storeRoote = []
        const checkMap = []
        const Base64 = require('js-base64').Base64
        const storeMenu = Cookies.get('STORE_MENU')
        const userEdition = Cookies.get('IS_JURISDICTION')
        const independent = Cookies.get('independent')
        const FATHER_TOTALCHANEL = Cookies.get('FATHER_TOTALCHANEL')
        const FATHER_TOTALPLUGINS = Cookies.get('FATHER_TOTALPLUGINS')
        const agent_id = Cookies.get('agent_id')
        const INDEX_LAYOUT = Cookies.get('INDEX_LAYOUT')
        const hasChannel = isRouterMap.findIndex(item => { return item.path === '/channel' })
        const hasApplication = isRouterMap.findIndex(item => { return item.path === '/application' })
        // const hasPermission = isRouterMap.findIndex(item => { return item.path === '/permission' })
        const hasfinance = isRouterMap.findIndex(item => { return item.path === '/finance' })
        // const hasGroupBuy = isRouterMap.findIndex(item => { return item.path === '/groupBuy' })
        // const settingSystem = Cookies.get('IS_SYSTEM')
         //切换平台或者扫码登录时渠道有可能不显示
        if (FATHER_TOTALCHANEL) {
          if (hasChannel === -1) {
            isRouterMap.push(...asyncChannleMap)
          } 
          // else {
          //   isRouterMap.splice(hasChannel, 1)
          // }
        }
        //根据cooking里的agent_id
        if(agent_id){
          if(hasfinance===-1){
            isRouterMap.push(...asyndailiMap)
          }
        }

        if (FATHER_TOTALPLUGINS) {
          if (hasApplication === -1) {
            // push应用
            isRouterMap.push(...asyncPluginsMap)
          } else {
            isRouterMap.splice(hasApplication, 1)
          }
        }
        // if(this.$route.query.h_aid&& this.$route.query.store_user_id){
        //   if(hasPermission===-1){
        //     isRouterMap.splice(hasApplication, 1)
        //   }
        // }

        if (INDEX_LAYOUT) {
          commit('SET_INDEX_LAYOUT', 1)
        }
        if (storeMenu && typeof storeMenu === 'string') {
          const storeMenuBase = JSON.parse(Base64.decode(storeMenu))
          // console.log('12333333333333333333333333311111', storeMenuBase)
          // commit('SET_GROUP', storeMenuBase && storeMenuBase.plugin && storeMenuBase.plugin.cgp && storeMenuBase.plugin.cgp.open ? storeMenuBase.plugin.cgp.open : false)
          // localStorage.setItem('isGroup', storeMenuBase && storeMenuBase.plugin && storeMenuBase.plugin.cgp && storeMenuBase.plugin.cgp.open ? storeMenuBase.plugin.cgp.open : false)
          // console.log(storeMenuBase && storeMenuBase.plugin && storeMenuBase.plugin.cgp && storeMenuBase.plugin.cgp.open, 'storeMenuBase && storeMenuBase.plugin && storeMenuBase.plugin.cgp && storeMenuBase.plugin.cgp.open ? storeMenuBase.plugin.cgp.open')
          if (!!storeMenuBase && typeof storeMenuBase === 'object') {
            const keysMap = Object.keys(storeMenuBase)
            if (Array.isArray(keysMap) && keysMap.length > 0) {
              // console.log(keysMap, '=================keysMap')
              keysMap.map(routerPath => {
                if (routerPath !== 'edition') {
                  const [isHashPath] = storeMenuHash[`${routerPath}`]
                  // console.log(isHashPath, '=================isHashPath')
                  // console.log(storeMenuHash, '=================storeMenuHash')
                  const itemPath = storeMenuBase[`${routerPath}`]
                  // console.log(itemPath, '=================itemPath')
                  let firstPath = null
                  if (itemPath) {
                    const itemPathKeys = Object.keys(itemPath)
                    // console.log(itemPathKeys, '=======111====itemPathKeys')
                    if (Array.isArray(itemPathKeys) && itemPathKeys.length > 0) {
                      itemPathKeys.map((childPath, childIndex) => {
                        const childItem = itemPath[`${childPath}`]
                        if (storeMenuHash[`${childPath}`] && !childItem.open) {
                          const isHashChild = storeMenuHash[`${childPath}`]
                          storeMap.push(...isHashChild)
                        } else if (typeof firstPath !== 'number') {
                          firstPath = childIndex
                        }
                      })
                    }

                    if (typeof firstPath === 'number') {
                      // storeRoote.push({ 'key': `${isHashPath}`, 'redirect': storeMenuHash[`${itemPathKeys[firstPath]}`][0] })
                      storeRoote.push({ 'key': `${isHashPath}`, 'hidden' : true,'redirect': storeMenuHash[`${itemPathKeys[firstPath]}`] })
                    }
                  }
                }
              })
            }
          }
        }

        if (storeMap.length > 0) {
          accessedRouters = filterBaseRouter(isRouterMap, storeMap, storeRoote)
        } else {
          accessedRouters = isRouterMap
        }
        if (accessedRouters.length > 0) {
          accessedRouters.map(route => {
            const { path, meta, children,hidden } = route
            if (children && children.length > 0 && meta.groupMenu) {
              const [firstPage] = children
              firstPage.meta.groupMenuTitle = meta.groupMenu
              route.redirect = `${path}/${firstPage.path}`
              // route.hidden = hidden
            }
          })
        }
        // console.log("肥肚肚的",is_super,jurisdiction)
        
       
        if (is_super === 0 && typeof jurisdiction === 'object') {
          const routerPath = jurisdiction
          if (Array.isArray(routerPath) && routerPath.length > 0) {
            routerPath.map(item => {
              const { path, menu, checkAll, checkList, isIndeterminates } = item
              if (path === '/dashboard' && (checkAll === 'true' || isIndeterminates === 'true')) {
                resetDashboard = false
              }
              if (Array.isArray(checkList) && checkList.length > 0) {
                checkMap.push(...checkList)
              }
              if (Array.isArray(menu) && menu.length > 0) {
                menu.map(childItem => {
                  const { path: childPath } = childItem
                  pathMap.push(childPath)
                })
              }
              pathMap.push(path)
            })
            // console.log('ssssssssssss就回放回放回放回放', accessedRouters)

            accessedRouters = filterBaseRouter(isRouterMap, jurisdiction, pathMap, storeMap, checkMap)
           
          }
        }
          //处理权限是否展示
        if (userEdition && accessedRouters.findIndex((item) => { return item.path === '/permission' }) === -1) {
          accessedRouters.push(...asyncUserEditionMap)
        }
        // if(agent_id && accessedRouters.findIndex((item) => { return item.path == '/finance' }) === -1){
        //   accessedRouters.push(...asyndailiMap)
        // }
        // console.log("这是最终路由吗？",accessedRouters)
        //判断是否是微擎版，是微擎版就把设置下面的计划任务打开，否则关闭
        if(!userEdition){
          accessedRouters.map(item=>{
            if(item.path==='/setting'){
              item.children.map(value=>{
                console.log("9+++++++++++......",value)
                if(value.path==='renwuing'){
                  value.hidden = false
                }
              })
            }
          })
        }
        // accessedRouters.map(item=>{
        //   console.log("kjdsfdshf和豆腐干后端返",item)
        //   if(item.path==='/finance'){
        //     item.hidden = false
        //   }
        //   if(item.path==='/agentsetting'){
        //     item.hidden = true
        //   }
        // })
        // console.log("翻江倒海是否单独",rootState.user.h_aid!='')
        //   //h_aid有值，那就是代理登录
        // if(rootState.user.h_aid!=''){
        //   accessedRouters.map(item=>{
        //     console.log("fdshfdj分段函数发京东好店=====",item)
        //     // if(item.path==='/setting'){
        //     //   item.children.map(value=>{
        //     //     console.log("9+++++++++++......",value)
        //     //     if(value.path==='renwuing'){
        //     //       value.hidden = false
        //     //     }
        //     //   })
        //     // }
        //   })
        // }
        // 根据后端生成的COOKIE(IS_SYSTEM)来控制独立版的性能优化二级菜单是否显示
        // 默认不显示，如果有COOKIE(IS_SYSTEM)则证明需要显示，遍历全局路由找到设置的中的子集路由性能优化，进行hidden的控制
        // if (settingSystem) {
        //   accessedRouters.map(value => {
        //     if (value.path === '/setting') {
        //       value.children.map(value => {
        //         if (value.path === 'optimizationSettings') {
        //           value.hidden = false
        //         }
        //       })
        //     }
        //   })
        // }
        commit('SET_ROUTERS', { routers: accessedRouters, reset: resetDashboard, is_super,rootState })
        resolve()
      })
    }
  }
}

export default permission
